<template>
  <div
    v-if="localeConfig && showLangSwitch"
    class="language-select"
  >
    <!-- PC端显示 -->
    <el-select
      v-if="!isMobile()"
      v-model="currentLang"
      size="default"
      style="width: 120px"
      @change="changeLang"
    >
      <el-option
        v-for="lang in availableLanguages"
        :key="lang.code"
        :label="lang.name"
        :value="lang.code"
      />
    </el-select>

    <!-- 移动端显示 -->
    <template v-else>
      <div
        class="mobile-lang"
        @click="showPopup = true"
      >
        <el-icon size="20">
          <TablerLanguage />
        </el-icon>
      </div>

      <van-popup
        v-model:show="showPopup"
        closeable
        position="bottom"
        round
      >
        <div class="popup-header">
          <span class="title">{{ $t("common.operation") }}</span>
        </div>
        <van-cell-group>
          <van-cell
            v-for="lang in availableLanguages"
            :key="lang.code"
            :class="{ active: currentLang === lang.code }"
            :title="lang.name"
            @click="selectMobileLang(lang)"
          >
            <template #right-icon>
              <van-icon
                v-if="currentLang === lang.code"
                class="check-icon"
                name="success"
              />
            </template>
          </van-cell>
        </van-cell-group>
        <div class="popup-footer">
          <van-button
            block
            round
            @click="showPopup = false"
          >
            {{ $t("common.cancel") }}
          </van-button>
        </div>
      </van-popup>
    </template>
  </div>
</template>
<script lang="ts" setup>
import { inject, onMounted, ref, watch } from "vue";
import { allLanguages, FORM_LANG_KEY } from "@/views/formgen/utils/formI18n";
import { SHOW_LANG_SWITCH_KEY } from "../types/constants";
import { changeLocale, i18n } from "@/i18n";
import { isMobile } from "@/utils/other";
import TablerLanguage from "~icons/tabler/language";
import { useUserFormInject } from "@/views/formgen/components/GenerateForm/hooks/useUserFormInject";

interface Props {
  formKey?: string;
}

const props = withDefaults(defineProps<Props>(), {
  formKey: ""
});

const emit = defineEmits(["change"]);

const userFormStore = useUserFormInject();

const { localeConfig, currentLang } = userFormStore;

// 可用的语言列表
const availableLanguages = ref(allLanguages.filter(lang => localeConfig.value?.langCodes.includes(lang.code)));

const i18nCodeMap: Record<string, string> = {
  "zh-TW": "zh-tw",
  "en-US": "en",
  "zh-CN": "zh-cn",
  "ja-JP": "ja",
  "ko-KR": "ko",
  "de-DE": "de",
  "fr-FR": "fr"
};

// 显示vant弹出层
const showPopup = ref(false);
const showLangSwitch = inject(SHOW_LANG_SWITCH_KEY, false);

// 选择语言（移动端）
const selectMobileLang = (lang: { code: string }) => {
  changeLang(lang.code);
  showPopup.value = false;
};

// 切换语言
const changeLang = (langCode: string) => {
  currentLang.value = langCode;
  // 将语言存储到 sessionStorage
  sessionStorage.setItem(FORM_LANG_KEY + props.formKey, langCode);
  changeLocale(i18nCodeMap[langCode]);
  i18n.global.locale.value = i18nCodeMap[langCode];
  // 触发变更事件
  emit("change", langCode);
};

watch(
  () => currentLang.value,
  newVal => {
    if (!newVal || !showLangSwitch.value) {
      return;
    }
    console.log("newVal", newVal);
    changeLocale(i18nCodeMap[newVal]);
    i18n.global.locale.value = i18nCodeMap[newVal];
  },
  {
    immediate: true
  }
);

// 组件挂载时，从 sessionStorage 中获取已保存的语言
onMounted(() => {
  const savedLang = sessionStorage.getItem(FORM_LANG_KEY + props.formKey);
  if (savedLang && localeConfig.value?.langCodes.includes(savedLang)) {
    currentLang.value = savedLang;
    emit("change", savedLang);
  }
});
</script>
<style lang="scss" scoped>
.language-select {
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 100;
}

:deep(.van-cell.active) {
  color: var(--van-primary-color);
}

.popup-header {
  text-align: center;
  padding: 16px;
  font-size: 16px;
  font-weight: 500;
  border-bottom: 1px solid #eee;
}

.popup-footer {
  padding: 16px;

  .van-button {
    height: 40px;
    font-size: 16px;
  }
}

.check-icon {
  color: var(--van-primary-color);
}

.mobile-lang {
  width: 40px;
  height: 40px;
  background: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;

  .van-icon {
    font-size: 20px;
    color: var(--van-primary-color);
  }

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }

  &:active {
    transform: translateY(0);
  }
}

// 移动端
@media (max-width: 768px) {
  .language-select {
    right: 10px;
    top: 5px;
  }
}
</style>
